package nu.mine.tbje.easyEDT;

import org.apache.shale.view.AbstractViewController;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import javax.faces.context.FacesContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/***
 * @author Tbje
 *
 */
public class Today extends AbstractViewController{
	// une liste pour remplir le tableau 
	private List classes;
	private Edt edt;

	public List getClasses() {
		int id = 870;
		Date date;
		SimpleDateFormat d = new SimpleDateFormat("ddMMyyyy");
		FacesContext fc = FacesContext.getCurrentInstance();
		HttpServletRequest request = (HttpServletRequest)fc.getExternalContext().getRequest();
        Cookie cookie = (Cookie)fc.getExternalContext().getRequestCookieMap().get("groupeId");
		try {
			id = Integer.parseInt(request.getParameter("id"));
		} catch (NumberFormatException e) {
	        if (cookie != null) {
	        	try {
					id = Integer.parseInt(cookie.getValue());
				} catch (NumberFormatException e1) {
					id = 870;
				}
	        }
		}
		try {
			String sDate = request.getParameter("date");
			if (sDate==null) throw new Exception("Error");
			date = d.parse(sDate);
		} catch (Exception e1) {
			Calendar cal = GregorianCalendar.getInstance();
			cal.setTime(new Date());
			switch (cal.get(Calendar.DAY_OF_WEEK)) {
			case Calendar.SATURDAY:
				cal.add(Calendar.DAY_OF_MONTH, 2);
				break;
			case Calendar.SUNDAY:
				cal.add(Calendar.DAY_OF_MONTH, 1);
				break;
			default:
				break;
			}
			date = cal.getTime();
		}
		try {
			Edt edt = new Edt();
			edt.setLogin("*****");
			edt.setPass("*****");
			edt.doLogin();
			edt.doInit();
			edt.setIdAndCat("trainee", id);
			edt.setDisplayOptions();
			edt.setWeek(getWeek(date));
			InputStream i = edt.getData();

			return Edt.parse(i);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public void setClasses(List classes) {
		this.classes = classes;
	}

	private int getWeek(Date date){
		Calendar cal = GregorianCalendar.getInstance();
		cal.setTime(date);
		return cal.get(Calendar.WEEK_OF_YEAR);
	}

	
}
